package com.my.commonlib.util;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import com.my.commonlib.BaseApplication;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
public class FSManager {
	/**
	 * 静默打开一个文件写入的流，打开失败返回 null 这样做是为了 写入文件时减少代码的行数，免得老是要 try 和 catch
	 * 
	 * @param fileFullPath 文件的完整路径
	 * @return FileOutputStream 文件写入的流
	 */
	public static FileOutputStream getFileOutPutStream(String fileFullPath) {
		if (TextUtils.isEmpty(fileFullPath)) {
			return null;
		}

		try {
			return new FileOutputStream(fileFullPath);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 判断一个文件是否存在
	 * 
	 * @param fileFullPath 文件的完整路径
	 * @return boolean 如果文件存在则返回 true，否则 false
	 */
	public static boolean isFile(String fileFullPath) {
		if (TextUtils.isEmpty(fileFullPath)) {
			return false;
		}

		File file = new File(fileFullPath);
		return file.isFile();
	}

	/**
	 * 删除一个文件（若给定路径不存在也返回 true）
	 * 
	 * @param fileFullPath 文件的完整路径
	 * @return boolean 如果文件不存在或删除成功则返回 true，否则 false
	 */
	public static boolean removeFile(String fileFullPath) {
		if (TextUtils.isEmpty(fileFullPath)) {
			return true;
		}

		File file = new File(fileFullPath);
		if (file.isDirectory()) {
			return false;
		} else if (!file.isFile()) {
			return true;
		}

		return file.delete();
	}

	/**
	 * 判断一个目录是否存在
	 * 
	 * @param folderFullPath 目录的完整路径
	 * @return boolean 如果目录存在则返回 true，否则 false
	 */
	public static boolean isDir(String folderFullPath) {
		if (TextUtils.isEmpty(folderFullPath)) {
			return false;
		}

		File file = new File(folderFullPath);
		return file.isDirectory();
	}

	/**
	 * 静默关闭一个文件写入的流 这样做是为了 写入文件时减少代码的行数，免得老是要 try 和 catch
	 * 
	 * @param fos 文件写入的流
	 */
	public static void closeFileOutPutStream(FileOutputStream fos) {
		try {
			if (null != fos) {
				fos.close();
			}
		} catch (Exception e) {
		}
	}
	/**
	 * 读取本地字节数据(/assets 目录下)
	 * 
	 * @author agger
	 * @date 2014-06-30
	 * @param URL 相对 /assets 目录下的文件路径
	 * @return byte[] 读取的字节数据
	 * @throws
	 */
	public static byte[] loadFileBytes(String URL) {
		if (URL == null || URL.length() < 1) {
			return null;
		}

		try {
			AssetManager assetManager = BaseApplication.getApp().getAssets();
			InputStream fileInputStream = assetManager.open(URL);
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			byte[] buffer = new byte[4096];
			int i;

			while (-1 != (i = fileInputStream.read(buffer))) {
				bo.write(buffer, 0, i);
			}

			return bo.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 读取本地字符串数据(/assets 目录下)
	 * 
	 * @author agger
	 * @date 2014-06-30
	 * @param URL 相对 /assets 目录下的文件路径
	 * @return String 读取的字符串数据
	 * @throws
	 */
	public static String loadFileString(String URL) {
		if (URL == null || URL.length() < 1) {
			return "";
		}

		try {
			AssetManager assetManager = BaseApplication.getApp().getAssets();
			InputStream fileInputStream = assetManager.open(URL);
			ByteArrayOutputStream bo = new ByteArrayOutputStream();

			byte[] buffer = new byte[4096];
			int i;

			while (-1 != (i = fileInputStream.read(buffer))) {
				bo.write(buffer, 0, i);
			}

			return bo.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}
	/**
	 * 读取字符串数据(指定 目录下)
	 * 
	 */
	public static String loadFileToString(String URL) {
		if (URL == null || URL.length() < 1) {
			return "";
		}
		
		try {
			File file = new File(URL);
			
			InputStream fileInputStream =  new FileInputStream(file);
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			
			byte[] buffer = new byte[4096];
			int i;
			
			while (-1 != (i = fileInputStream.read(buffer))) {
				bo.write(buffer, 0, i);
			}
			
			return bo.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
	}
	
	
	public static Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}
	
	public static boolean saveMyBitmap(Bitmap mBitmap, String suffix) {
		boolean flag = true;
		File zqmf = new File(getSDPath() + "/zqmf/");
		if (!zqmf.exists()) {
			zqmf.mkdirs();
		}
		File f = new File(zqmf, System.currentTimeMillis() + ".jpg");
		FileOutputStream fOut = null;
		try {
			f.createNewFile();
			fOut = new FileOutputStream(f);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
		} catch (IOException e) {
			flag = false;
			e.printStackTrace();
		}
		try {
			fOut.flush();
			fOut.close();
		} catch (IOException e) {
			flag = false;
			e.printStackTrace();
		}
		return flag;
	}

	public static boolean saveImageToGallery(Context context, Bitmap bmp) {
		boolean flag = false;
	    // 首先保存图片
	    File appDir = new File(getSDPath(), "zqmf");
	    if (!appDir.exists()) {
	        appDir.mkdir();
	    }
	    String fileName = System.currentTimeMillis() + ".jpg";
	    File file = new File(appDir, fileName);
	    try {
	        FileOutputStream fos = new FileOutputStream(file);
	        bmp.compress(CompressFormat.JPEG, 100, fos);
	        fos.flush();
	        fos.close();
	        flag = true;
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
		}

	    // 其次把文件插入到系统图库
	    flag = noticeImage(context, file);
	    return flag;
	}

	public static boolean noticeImage(Context context, File file){
		boolean flag = true;
		try {
	        MediaStore.Images.Media.insertImage(context.getContentResolver(),
					file.getAbsolutePath(), file.getName(), null);
	    } catch (FileNotFoundException e) {
	    	flag = false;
	        e.printStackTrace();
	    }
	    // 最后通知图库更新
	    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
	    return flag;
	}

	public static boolean writeFile(byte[] buffer, String folder,
			String fileName) {
		boolean writeSucc = false;

		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);

		String folderPath = "";
		if (sdCardExist) {
			folderPath = Environment.getExternalStorageDirectory()
					+ File.separator + folder + File.separator;
		} else {
			writeSucc = false;
		}

		File fileDir = new File(folderPath);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}

		File file = new File(folderPath + fileName);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(buffer);
			writeSucc = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return writeSucc;
	}
	
	
	
	/**
	    * 解压缩功能.
	    * 将zipFile文件解压到folderPath目录下.
	    * @throws Exception
	*/
    public static int upZipFile(File zipFile, String folderPath)throws ZipException,IOException {
        ZipFile zfile=new ZipFile(zipFile);
        Enumeration zList=zfile.entries();
        ZipEntry ze=null;
        byte[] buf=new byte[1024];
        while(zList.hasMoreElements()){
            ze=(ZipEntry)zList.nextElement();
            if(ze.isDirectory()){
                Logger.d("upZipFile", "ze.getName() = "+ze.getName());
                String dirstr = folderPath + ze.getName();
                //dirstr.trim();
                dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
                Logger.d("upZipFile", "str = "+dirstr);
                File f=new File(dirstr);
                f.mkdir();
                continue;
            }
            Logger.d("upZipFile", "ze.getName() = "+ze.getName());
            OutputStream os=new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, ze.getName())));
            InputStream is=new BufferedInputStream(zfile.getInputStream(ze));
            int readLen=0;
            while ((readLen=is.read(buf, 0, 1024))!=-1) {
                os.write(buf, 0, readLen);
            }
            is.close();
            os.close();    
        }
        zfile.close();
        Logger.d("upZipFile", "finishssssssssssssssssssss");
        return 0;
    }

    /**
    * 给定根目录，返回一个相对路径所对应的实际文件名.
    * @param baseDir 指定根目录
    * @param absFileName 相对路径名，来自于ZipEntry中的name
    * @return java.io.File 实际的文件
	*/
    public static File getRealFileName(String baseDir, String absFileName){
        String[] dirs=absFileName.split("/");
        File ret=new File(baseDir);
        String substr = null;
        if(dirs.length>1){
            for (int i = 0; i < dirs.length-1;i++) {
                substr = dirs[i];
                try {
                    //substr.trim();
                    substr = new String(substr.getBytes("8859_1"), "GB2312");
                    
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                ret=new File(ret, substr);
                
            }
            Logger.d("upZipFile", "1ret = "+ret);
            if(!ret.exists())
                ret.mkdirs();
            substr = dirs[dirs.length-1];
            try {
                //substr.trim();
                substr = new String(substr.getBytes("8859_1"), "GB2312");
                Logger.d("upZipFile", "substr = "+substr);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            ret=new File(ret, substr);
            Logger.d("upZipFile", "2ret = "+ret);
            return ret;
        }
        return ret;
    }

	public static Bitmap drawable2Bitmap(Drawable drawable) {
		if (drawable instanceof BitmapDrawable) {
			return ((BitmapDrawable) drawable).getBitmap();
		} else if (drawable instanceof NinePatchDrawable) {
			Bitmap bitmap = Bitmap
					.createBitmap(
							drawable.getIntrinsicWidth(),
							drawable.getIntrinsicHeight(),
							drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
									: Bitmap.Config.RGB_565);
			Canvas canvas = new Canvas(bitmap);
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());
			drawable.draw(canvas);
			return bitmap;
		}
		return null;
	}

	/**
	 * 递归删除文件
	 * @param file
	 */
	public static void RecursionDeleteFile(File file){
       try {
			if(file.isFile()){
	            file.delete();
	            return;
	        }
	        if(file.isDirectory()){
	            File[] childFile = file.listFiles();
	            if(childFile == null || childFile.length == 0){
	                file.delete();
	                return;
	            }
	            for(File f : childFile){
	                RecursionDeleteFile(f);
	            }
	            file.delete();
	        }
	   	} catch (Exception e) {
	   		e.printStackTrace();
	   	}
    }
	
	/**
	 * 如果 文件目录不存在 就创建目录
	 * 
	 */
	
	public static void createDir(String path){
		try{
			if(null != path && !"".equals(path)){
				File file = new File(path);
				if(!file.exists()){
					file.mkdirs();
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**获得sd卡的根目录  */
	public static String getSDPath() {
		try {
			File sdDir = null;
			// 判断sd卡是否存在
			if (isExternalStorageAvaliable()) {
				sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
			}
			return sdDir.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static boolean isExternalStorageAvaliable(){
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		} else {
			return false;
		}
	}


	/**
	 * 获取文件大小
	 *
	 * @param filePath
	 * @return
	 */
	public static long getFileSize(String filePath) {
		long size = 0;

		File file = new File(filePath);
		if (file != null && file.exists()) {
			size = file.length();
		}
		return size;
	}

	/**
	 * 获取文件大小
	 *
	 * @param size
	 *            字节
	 * @return
	 */
	public static String getFileSize(long size) {
		if (size <= 0)
			return "0";
		java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
		float temp = (float) size / 1024;
		if (temp >= 1024) {
			return df.format(temp / 1024) + "M";
		} else {
			return df.format(temp) + "K";
		}
	}


	/**
	 * 获取文件大小
	 *
	 * @param size
	 *            字节
	 * @return
	 */

	public static float  getFileSizes(long size) {
		if (size <= 0)
			return 0;
		java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
		float temp = (float) size / 1024;
		if (temp >= 1024) {
			return temp / 1024 ;
		} else {
			return 1;
		}
	}
}